package cz.data.common.feign;

import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.encoding.BaseRequestInterceptor;
import org.springframework.cloud.openfeign.encoding.FeignClientEncodingProperties;

import java.util.Collection;
import java.util.Map;

public class RequestCompressionInterceptor extends BaseRequestInterceptor {
    private final Logger log = LoggerFactory.getLogger(RequestCompressionInterceptor.class);

    protected RequestCompressionInterceptor(FeignClientEncodingProperties properties) {
        super(properties);
    }

    @Override
    public void apply(RequestTemplate template) {
        if (this.requiresCompression(template)) {
            log.debug("RequestTemplate add header [Accept-Encoding: gzip,deflate]");
            this.addHeader(template, "Accept-Encoding", "gzip", "deflate");
        }
    }

    private boolean requiresCompression(RequestTemplate template) {
        Map<String, Collection<String>> headers = template.headers();
        return this.matchesMimeType(headers.get("Content-Type")) && this.contentLengthExceedThreshold(headers.get("Content-Length"));
    }

    private boolean contentLengthExceedThreshold(Collection<String> contentLength) {
        try {
            if (contentLength != null && contentLength.size() == 1) {
                String strLen = contentLength.iterator().next();
                long length = Long.parseLong(strLen);
                return length > (long) this.getProperties().getMinRequestSize();
            } else {
                return false;
            }
        } catch (NumberFormatException var5) {
            return false;
        }
    }

    private boolean matchesMimeType(Collection<String> contentTypes) {
        if (contentTypes != null && contentTypes.size() != 0) {
            if (this.getProperties().getMimeTypes() != null && this.getProperties().getMimeTypes().length != 0) {
                String[] var2 = this.getProperties().getMimeTypes();
                int var3 = var2.length;
                for (int var4 = 0; var4 < var3; ++var4) {
                    String mimeType = var2[var4];
                    if (contentTypes.contains(mimeType)) {
                        return true;
                    }
                }
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}
